import requests
import sqlite3
from bs4 import BeautifulSoup
import hashlib
import random

# 注册百度翻译账号并获取API Key和API Secret
API_KEY = 'API_KEY'
API_SECRET = 'API_SECRET'
API_URL = 'http://api.fanyi.baidu.com/api/trans/vip/translate'

# 读取HTML文件
with open('1.html', 'r', encoding='utf-8') as file:
    html = file.read()

# 提取HTML中的英文文本
soup = BeautifulSoup(html, 'html.parser')
english_text = [text for text in soup.stripped_strings if text.isalpha()]

# 连接到SQLite数据库
conn = sqlite3.connect('translations.db')
c = conn.cursor()

# 创建表格
c.execute('''CREATE TABLE IF NOT EXISTS translations
             (english text, chinese text)''')

# 将英文文本翻译为中文
chinese_text = []
for text in english_text:
    # 先从数据库读取翻译结果
    c.execute("SELECT chinese FROM translations WHERE english=?", (text,))
    result = c.fetchone()
    if result:
        chinese_text.append(result[0])
    else:
        try:
            # 发送请求至百度翻译API
            salt = str(random.randint(100000, 999999))
            sign = API_KEY + text + salt + API_SECRET
            sign = hashlib.md5(sign.encode()).hexdigest()
            response = requests.get(API_URL, params={
                'q': text,
                'from': 'en',
                'to': 'zh',
                'appid': API_KEY,
                'salt': salt,
                'sign': sign
            })
            # 从返回结果中提取中文翻译
            chinese = response.json()['trans_result'][0]['dst']
            chinese_text.append(chinese)
            # 将翻译结果保存到数据库
            c.execute("INSERT INTO translations VALUES (?, ?)", (text, chinese))
            conn.commit()
        except:
            # 发生异常时，将该文本留空
            chinese_text.append('')
        
# 替换HTML中的英文文本为中文翻译
for index, text in enumerate(english_text):
    html = html.replace(text, chinese_text[index])

# 保存翻译后的HTML
with open('index_chinese.html', 'w', encoding='utf-8') as file:
    file.write(html)

# 关闭数据库
# 连接
conn.close()